<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<%@ taglib prefix="his_fns" uri="/WEB-INF/tlds/his_fns.tld" %>

<div class="app">
    <section class="layout">
        <section class="main-content col-lg-12" id="drugExportDiv">
            <div class="content-wrap">
                <div class="wrapper" style="bottom: 50px;">
                    <ul class="nav nav-tabs">
                        <li class="active">
                            <a href="#" onclick="loadDiv('mainCenterDiv','${ctx}/drug/drugExport/index')">出库处理</a>
                        </li>
                    </ul>
                    <section class="panel panel-default">
                        <div class="panel-body">
                            <div class="table-responsive no-border">
                                <div class="datatable-top">
                                    <div class="pull-left">
                                        <form:form id="searchForm" modelAttribute="drugExportDetail"
                                                   onsubmit="return loadDivForm('mainCenterDiv','searchFormDict','${ctx}/drug/drugExport/index');"
                                                   method="post" class="form-inline">
                                            <div class="form-group">
                                                <label class=" control-label">出库类别：</label>
                                                <form:select path="drugInoutClass.type" id="masterClass" htmlEscape="false" class="form-control" maxlength="1" data-parsley-required="true"
                                                        onchange="loadSupplier()">
                                                    <form:options items="${his_fns:getExportClassDictList()}" itemLabel="label" itemValue="label" htmlEscape="false" />
                                                </form:select>
                                            </div>

                                            <div class="form-group">
                                                <label class=" control-label">出库日期：</label>
                                                <input name="exportDate" id="expireDate1" htmlEscape="false" class="form-control Wdate" data-parsley-required="true" readonly/>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">收货单位：</label>
                                                <select class="form-control" id="supplier"></select>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">出库金额总计:</label>
                                                <input class="form-control" id="totalMoney" type="text" readonly>
                                            </div>
                                            <div class="form-group">
                                                    <input id="btnSubmit" class="btn btn-primary" type="button" onclick="saveExport()" value="保存"/>
                                                    <input id="addDrug" class="btn btn-primary" type="button" value="添加" onclick="addExportItem()"/>
                                            </div>
                                        </form:form>
                                    </div>
                                </div>
                                <table id="contentTable" class="table table-bordered table-striped mg-t datatable">
                                    <thead>
                                    <tr>
                                        <th hidden>jsonText</th>
                                        <th >药品编码</th>
                                        <th>药品名称</th>
                                        <th>包装数量</th>
                                        <th>包装规格</th>
                                        <th>包装单位</th>
                                        <th>最小规格</th>
                                        <th>最小单位</th>
                                        <th>厂家</th>
                                        <th>进价</th>
                                        <th>售价</th>
                                      <%--  <th>折扣</th>--%>
                                        <th>批号</th>
                                        <th>有效期</th>
                                        <th>出库数量(大包装)</th>
                                        <th>当前库存</th>
                                        <th>入库单号</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                </table>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </section>
        <%--右侧药品出库明细列表--%>
        <section class="main-content col-lg-4" style="display: none" id="drugExportRightDiv">
            <div class="content-wrap" id="rigthCenterDiv">
            </div>
        </section>
    </section>
</div>
<script type="text/javascript">
    loadSupplier();
    function loadSupplier() {
        $("#supplier").html("");
        var exportClass = $('#masterClass').val();  //出库类别
        $.ajax({
            url: '${ctx}/drug/drugExport/getSupplierList?type=' + exportClass,
            type: 'get',
            contentType: 'application/json',
            async: true,
            success: function (data, textStatus, jqXHR) {
                if (data.length > 0) {
                    if(typeof(data[0].supplierJc) == 'undefined'){
                        $.each(data, function (index, item) {
                            $("#supplier").append("<option value='" + item.storageCode + "'>" + item.storageName + "</option>");
                        });
                    }else{
                        $.each(data, function (index, item) {
                            $("#supplier").append("<option value='" + item.id + "'>" + item.supplierJc + "</option>");
                        });
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    }

    //设置出库日期为当前时间,不能编辑
    var date = new Date();
    var nowMonth = "";
    if(date.getMonth()+1 <= 9){
        nowMonth = "0" + (date.getMonth() + 1) + "";
    }else{
        nowMonth = (date.getMonth() + 1) + "";
    }
    var hours = "";
    if(date.getHours() < 10){
        hours = "0" + date.getHours();
    }else{
        hours = date.getHours();
    }
    var minutes = "";
    if(date.getMinutes() < 10){
        minutes = "0" + date.getMinutes();
    }else{
        minutes = date.getMinutes();
    }
    var seconds = "";
    if(date.getSeconds() < 10){
        seconds = "0" + date.getSeconds();
    }else{
        seconds = date.getSeconds();
    }
    var now = date.getFullYear() + "-" + nowMonth + "-" + date.getDate() + " " + hours + ":" + minutes + ":" + seconds;
    $('#expireDate1').val(now);
    //出库金额总计
    $('#totalMoney').val(0.00);
    /*库存单位补全*/
    autoCompleteFirm("storageName");
    function autoCompleteFirm(inputId){
        var url="${ctx}/drug/drugStorageDept/autoComplete";
        autoComplete(inputId,url,
                function(data){
                    var rows = [];
                    for(var i=0; i<data.length; i++){
                        rows[rows.length] = {
                            data:data[i],
                            value:data[i].id,
                            result:data[i].storageName
                        };
                    }
                    return rows;
                },function(data, i, max){
                    return data.storageName;
                },function(event,data,formatted){
                    $('#storageId').attr('value',data.id);
                });
    }

    //弹出右边增加药品明细框
    function addExportItem(){
        $("#drugExportDiv").attr("class","main-content col-lg-8");
        $("#drugExportRightDiv").show('normal');
        return loadDiv('rigthCenterDiv','${ctx}/drug/drugExport/form');
    }

    //删除一行药品
    function removeList(btn){
        var price=parseFloat($('#totalMoney').val());
        var td = $(btn).parent().parent().children().eq(0).text();
        $(btn).parent().parent().remove();
        var obj=$.parseJSON(td);
        //console.log(obj);
        var total = parseFloat(price).toFixed(2)-parseFloat(obj.retailPrice).toFixed(2)*parseInt(obj.quantityOut).toFixed(2);
        total = Math.round(parseFloat(total)* 100) / 100;
        $('#totalMoney').val(total);
    }

    //修改药品
    function updateList(btn){
        var price=parseFloat($('#totalMoney').val());
        var td = $(btn).parent().parent().children().eq(0).text();
        $("#drugExportDiv").attr("class","main-content col-lg-8");
        $("#drugExportRightDiv").show('normal');
        fillForm($("#inputForm"),td);
        $(btn).parent().parent().remove();
        var obj=$.parseJSON(td);
        var total = parseFloat(price).toFixed(2)-parseFloat(obj.retailPrice).toFixed(2)*parseInt(obj.quantityOut).toFixed(2);
        total = Math.round(parseFloat(total)* 100) / 100;
        $('#totalMoney').val(total);

    }

    function saveExport(){
        var exportClass = $("#masterClass").val();  //出库类别
        var receiver = $('#supplier').val();     //收货单位
        if (exportClass.replace(/(^s*)|(s*$)/g, "").length == 0 || exportClass == null || typeof(exportClass) == 'undefined') {
            toastr.error("出库类别不能为空,请选择");
            return ;
        }

        var list=$("table tr").find("td:eq(0)");
        var dataList=[];
        var data={};
        for (var i=0;i<list.length;i++){
            data=jQuery.parseJSON( list[i].innerText );
            var drugStock = {};
            drugStock.id = data['id'];
            drugStock.packageUnits=date['packageUnits'];
            drugStock.drugName = data['drugName'];
//            drugStock.discount = data.discount;
            drugStock.infoId = data['infoId'];
            drugStock.documentNo = data['documentNo'];
            drugStock.quantity = data['quantity'];//当前库存
            data.quantity = data['quantityOut'];//出库数量
            data.drugStock = drugStock;
            var drugPrice = {};
            //data.drugInfo = data['infoId'];
            drugPrice.retailPrice = data['retailPrice'];
            data.drugPrice = drugPrice;
            var drugExportMaster = {};
            drugExportMaster.receiver = receiver;
            drugExportMaster.exportClass = exportClass;
            drugExportMaster.documentNo = "";
            data.drugExportMaster = drugExportMaster;

            dataList.push(data);
        }

        var dataListJson = JSON.stringify(dataList);
        $.ajax({
            type: "POST",
            url: '${ctx}/drug/drugExport/saveExport',
            data:dataListJson,
            'contentType': 'application/json',
            dataType: "json",
            success: function (data) {
                if (data.code == "success") {
                    toastr.success("药品出库成功");
                    layer.open({
                        title: "需要打印单据吗?",
                        type: 1,
                        area: ['300px', '150px'],
                        fixed: false, //不固定
                        skin: 'layui-layer-rim',
                        maxmin: true,
                        content:"",
                        btn: ['确定', '取消'],
                        yes: function (index, layero) {
                            printPdf('${ctx}/drug/drugDetails/drugExportDetailsPrint?masterId='+data.data);
                        }, no: function (index) {
                            layer.close(index);
                        }
                    });
                    return loadDiv('mainCenterDiv', '${ctx}/drug/drugExport/index');
                } else {
                    toastr.error(data.data);
                }
            },
            error: function (data) {
                toastr.error('网络连接错误,请检查网络');
            }
        });
    }
</script>